import json
import pdb
import re

from common.setting import ensure_path_sep
from utils.mysqlUtils.db_pool import Database


def find_error(failure_info):
    user_message = ""
    match = re.search(r'"userMessage\\":\\"(.*)\\",\\"metadata', failure_info[0])
    if match:
        user_message = match.group(1)
        print(user_message)
    else:
        print("未找到匹配的 userMessage 值")
    return user_message

def remove_duplicates_and_count(lst):
    # 使用集合去重
    unique_elements = set(lst)

    # 统计每个元素的数目
    count_dict = {}
    for element in unique_elements:
        count_dict[element] = lst.count(element)

    return count_dict


class AllegroPublishAnalysisTestCase:
    strategy_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "HWY-ZH-GZ-RDS-strategy")
    category_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "zhcxkj_center_category_attribute_prod")
    db_java_test = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
    zhcxkj_center_product_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "HWY-ZH-GZ-RDS-Product")

    def test_allegro_publish_analysis(self, strategy_id, status):

        get_data = f"""
        select fail_msg
        from zhcxkj_center_strategy_comprehensive.t_publish_detail_allegro
        where strategy_id = %s
        and status = %s
--         limit 1
        """
        res = self.strategy_db.fetch_all_tuple(get_data, (strategy_id, status))
        # split("请求参数")[0]
        res_filter1 = tuple(filter(lambda x: "失败信息" in x[0], res))
        # res_filter2 = tuple(filter(lambda x:"未知场景信息" in x[0],res))
        res_map1 = list(map(find_error, res_filter1))
        # res_map2 = tuple(map(lambda x:json.loads(x[0].split("：")[1]),res_filter2))
        remove_duplicates_and_count1 = remove_duplicates_and_count(res_map1)
        remove_duplicates_and_count_sort = sorted(remove_duplicates_and_count1.items(), key=lambda x: x[1], reverse=True)
        print()
        data_map = [(strategy_id,fail_msg,count)  for fail_msg,count in remove_duplicates_and_count_sort ]
        insert_sql = f"""
                INSERT  INTO monitor.`test_allegro_publish_analysis` ( 
                `strategy_id`, 
                `fail_msg`, 
                `count`)
                VALUES
        	    ( %s, %s, %s)
                """
        rows = self.db_java_test.execute_many(insert_sql, data_map)


if __name__ == '__main__':
    AllegroPublishAnalysisTestCase().test_allegro_publish_analysis(541, 5)

